const fs = require('fs');

// add url-route in /controllers:
function getPath ({position,dir,url}){
    
    return `${dir==='controllers38'?'':'/'+dir}${url.substring(position)}`
}

function addMapping(router, mapping,dir) {
    for (var url in mapping) {
        if (url.startsWith('GET ')) {

            // var path = url.substring(4);
            var path = getPath({position:4,dir,url});
            router.get(path, mapping[url]);
            console.log(`register URL mapping: GET ${path}`);
        } else if (url.startsWith('POST ')) {
            var path = getPath({position:5,dir,url});
            // var path = url.substring(5);
            router.post(path, mapping[url]);
            console.log(`register URL mapping: POST ${path}`);
        } else if (url.startsWith('PUT ')) {
            var path = getPath({position:4,dir,url});
            // var path = url.substring(4);
            router.put(path, mapping[url]);
            console.log(`register URL mapping: PUT ${path}`);
        } else if (url.startsWith('DELETE ')) {
            var path = getPath({position:7,dir,url});
            // var path = url.substring(7);
            router.del(path, mapping[url]);
            console.log(`register URL mapping: DELETE ${path}`);
        }
        else if (url.startsWith('PATCH ')) {

            var path = url.substring(6);
            router.patch(path, mapping[url]);
            console.log(`register URL mapping: PATCH ${path}`);
        } else {
            console.log(`invalid URL: ${url}`);
        }
    }
}

function addControllers(router, dir) {
    fs.readdirSync(__dirname + '/' + dir).filter((f) => {
        return f;
    }).forEach((f) => {
        fs.readdirSync(__dirname + '/' + dir + '/' + f).filter((f) => {
            return f.endsWith('.js');
        }).forEach((k) => {
            console.log(`process controller: ${k}...`);
            let mapping = require(__dirname + '/' + dir + '/' + f + '/' + k);
            addMapping(router, mapping,dir);
        })
    });
}

module.exports = function (dir) {
    let
        controllers_dir = dir || 'controllers',
        router = require('koa-router')();
    addControllers(router, controllers_dir);
    return { routes: router.routes(), allowedMethods: router.allowedMethods() };
};